package control

import (
	"net/http"
	"pro_cla_sql/model"
	"pro_cla_sql/util"
	"time"

	"github.com/dgrijalva/jwt-go"
)

var CSno string = ""

// Login 登陆
func Login(w http.ResponseWriter, r *http.Request) {
	w.Header().Set(`Content-Type`, `application/json`)
	w.Header().Set(`Access-Control-Allow-Origin`, `*`)
	r.ParseForm()
	sno := r.FormValue("sno")
	// print(sno)
	mod, err := model.Login(sno)
	if err != nil {
		w.Write(util.NewResult(util.Fail, "账号输入错误,请重试"))
		return
	}
	pass := r.FormValue("pass")
	if mod.Password != pass {
		w.Write(util.NewResult(util.Fail, "密码错误,请重试"))
		return
	}
	CSno = mod.Sno

	data := model.Jwt{
		Id:        mod.Id,
		Sno:       mod.Sno,
		Ismanager: mod.Ismanager,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(2 * time.Hour).Unix(), //1970
		},
	}
	jwts := jwt.NewWithClaims(jwt.SigningMethodHS256, data)
	token, err := jwts.SignedString([]byte(`k`))
	if err != nil {
		w.Write(util.NewResult(util.Fail, "token生成失败,请重试"))
		return
	}
	w.Write(util.NewResult(util.Success, `登陆成功`, token))
}
